 //
//  WBComposeViewController.swift
//  SinaWebo
//
//  Created by 亚杏 on 2017/6/1.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit
import SVProgressHUD

 /**
  加载视图控制器时，如果xib和控制器同名，默认的构造函数优先加载xib
  */
 //撰写微博控制器
class WBComposeViewController: UIViewController {

    //文本编辑视图
    @IBOutlet weak var textView: WBComposeTextView!
    //底部工具栏
    @IBOutlet weak var toolBar: UIToolbar!

    @IBOutlet var navItemLabel: UILabel!

    @IBOutlet weak var toolBarBottom: NSLayoutConstraint!

    lazy var emoticonView: XYXEmoticonInputView  = XYXEmoticonInputView.inputView { [weak self] (emoticonModel) in

        self?.textView.insertEmoticon(em: emoticonModel)
    }

    //键盘高度
    var rect: CGRect? = nil


    override func viewDidLoad() {
        super.viewDidLoad()

        //强行更新约束

            setupUI()

            //监听键盘 - UIWindow.h
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name:NSNotification.Name.UIKeyboardWillChangeFrame  , object: nil)



    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        textView.becomeFirstResponder()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()

    }
    

    //监听键盘变化
    @objc private func keyboardChanged(n: Notification) {

        //1.目标 rect
        rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        guard rect != nil ,
        let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
        else{
            return
        }

        //2.设置底部约束高度
        let offset = view.bounds.height - (rect?.origin.y)!
        toolBarBottom.constant = offset

        //3.动画更新约束
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }

    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @objc func close() {
        dismiss(animated: true, completion: nil)
    }


    lazy var sendBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("发布", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)

        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.gray, for: .disabled)

        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        btn.addTarget(self, action: #selector(sendMsg), for: .touchUpInside)

        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 35)

        return btn
        
    }()


    //发布微博
    @objc private func sendMsg() {

        let text = textView.emoticonText

        let image: UIImage? = nil //UIImage(named: "icon_small_kangaroo_loading_1")
        //FIXME:临时测试发布带图片微博
        WBNetworkManager.shared.postMessage(text: text, image: image) { (result, isSuccess) in
            print(result ?? "")

            let message = isSuccess ? "发布成功" : "网络不给力"
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.showInfo(withStatus: message)

            //如果发送成功，就延迟一段时间关闭当前端口
            if isSuccess {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                    self.close()
                    SVProgressHUD.setDefaultStyle(.light)
                    self.close()
                })
            }
        }
    }


    func setupUI() {

        view.backgroundColor = UIColor.white
        setupNav()
        setupToolBar()
    }

    //设置导航栏
    func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)

        sendBtn.isEnabled = false
        navigationItem.titleView = navItemLabel

    }

    //设置工具栏
    func setupToolBar() {
        var items = [UIBarButtonItem]()

        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        for s  in itemSettings {
            guard let imageName = s["imageName"] else {
                return
            }
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            let btn = UIButton()
            btn.setImage(image, for: .normal)
            btn.setImage(imageHL, for: .highlighted)
            btn.sizeToFit()

            //判断actionName
            if let actionName = s["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }

            //追加按钮
            items.append(UIBarButtonItem(customView: btn))

            //追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))

        }
        //删除末尾弹簧
        items.removeLast()


        toolBar.items = items
    }

    //点击toolbar上表情按钮
    @objc private func emoticonKeyboard() {

        //textView.inputView 是文本框的输入视图
        //如果使用系统默认的键盘，输入视图为 nil,宽度随便写，高度必须确定
//        let keyboardView = UIView (frame: CGRect(x: 0, y: 0, width: 100, height: (rect?.size.height)!))
//        keyboardView.backgroundColor = UIColor.red
        // inputView为nil，显示正常键盘
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil

        //刷新键盘视图
        textView.reloadInputViews()

    }

}

  extension WBComposeViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        sendBtn.isEnabled = textView.hasText
    }

 }
